package com.nidu.demo.dict.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.dict.convertor.DictTypeConvertor;
import com.nidu.demo.dict.gateway.DictTypeGateway;
import com.nidu.demo.dict.mapper.DictTypeMapper;
import com.nidu.demo.dict.mapper.dataobject.DictTypeDO;
import com.nidu.demo.dict.model.DictType;
import com.nidu.demo.dict.model.DictTypeCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Set;
import java.util.List;

@Component
@RequiredArgsConstructor
public class DictTypeGatewayImpl implements DictTypeGateway {

    private final DictTypeMapper mapper;
    private final DictTypeConvertor convertor;

    @Override
    @CacheEvict(cacheNames = {"dictType", "dictData"}, allEntries = true)
    public DictType create(DictType dictType) {
        DictTypeDO dictTypeDO = convertor.toDataObject(dictType);
        mapper.insert(dictTypeDO);
        return convertor.toDomainObject(dictTypeDO);
    }

    @Override
    @CacheEvict(cacheNames = {"dictType", "dictData"}, allEntries = true)
    public DictType update(DictType dictType) {
        DictTypeDO dictTypeDO = convertor.toDataObject(dictType);
        mapper.updateById(dictTypeDO);
        return convertor.toDomainObject(dictTypeDO);
    }

    @Override
    @CacheEvict(cacheNames = {"dictType", "dictData"}, allEntries = true)
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    @CacheEvict(cacheNames = {"dictType", "dictData"}, allEntries = true)
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    @Cacheable(cacheNames = "dictType", key = "'type:' + #type", unless = "#result == null")
    public DictType getByType(String type) {
        DictTypeDO dictTypeDO = mapper.selectByType(type);
        if(dictTypeDO == null){
            return null;
        }
        return convertor.toDomainObject(dictTypeDO);
    }

    @Override
    @Cacheable(cacheNames = "dictType", key = "'id:' + #id", unless = "#result == null")
    public DictType getById(Long id) {
        DictTypeDO dictTypeDO = mapper.selectById(id);
        if (dictTypeDO == null) {
            return null;
        }
        return convertor.toDomainObject(dictTypeDO);
    }

    @Override
    public List<DictType> listByCondition(DictTypeCriteria criteria) {
        LambdaQueryWrapper<DictTypeDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(criteria.getStatus() != null, DictTypeDO::getStatus, criteria.getStatus());
        wrapper.in(!CollUtil.isEmpty(criteria.getDictTypeIds()), DictTypeDO::getId, criteria.getDictTypeIds());

        wrapper.eq(!StrUtil.isEmpty(criteria.getType()), DictTypeDO::getType, criteria.getType());

        List<DictTypeDO> dictTypeDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(dictTypeDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(dictTypeDOS);
    }

    @Override
    public PageResponse<DictType> pageByCondition(DictTypeCriteria criteria) {
        // 创建查询条件
        LambdaQueryWrapper<DictTypeDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(criteria.getStatus() != null, DictTypeDO::getStatus, criteria.getStatus());

        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(DictTypeDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(DictTypeDO::getCreateTime, createTime[0], createTime[1]);
            }
        }

        wrapper.like(!StrUtil.isEmpty(criteria.getType()), DictTypeDO::getType, criteria.getType());

        // 创建分页对象，确保使用 DictTypeDO
        Page<DictTypeDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }
        mapper.selectPage(page, wrapper);
        List<DictType> dictTypes = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(dictTypes, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    @CacheEvict(cacheNames = {"dictType", "dictData"}, allEntries = true)
    public void updateStatus(Long id, Integer status) {
        DictTypeDO dictTypeDO = new DictTypeDO();
        dictTypeDO.setId(id);
        dictTypeDO.setStatus(status);
        mapper.updateById(dictTypeDO);
    }
    
}